<?php

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{

    const COUNT = 20;

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        /**
         * GroupName 根据 env 配置
         */
        $this->groupName('admin_groups')->times(self::COUNT)->make();
        $this->groupName('company_groups')->times(self::COUNT)->make();
        $this->groupName('hr_groups')->times(self::COUNT)->make();
    }

    private function groupName($groupName)
    {
        $this->groupName = $groupName;
        $this->groups = env(strtoupper($groupName));
        $this->roleNames = explode(',', $this->groups);

        return $this;
    }

    private function times($count)
    {
        $this->times = $count;

        return $this;
    }

    private function make()
    {
        $times = property_exists($this, 'times') ? $this->times : self::COUNT;
        $roleIDs = $this->getRoleIDsByNames($this->roleNames);

        $factory = factory(App\User::class, $this->groupName, $times)->create();
        $factory->each(function($user) use ($roleIDs) {
            $user->roles()->attach($roleIDs[array_rand($roleIDs)]);
        });
    }

    private function getRoleIDsByNames($names)
    {
        $query = DB::table('roles');

        foreach ($names as $name) {
            $query = $query->orWhere('name', $name);
        }

        return $query->lists('id');
    }
}
